package cn.zhx.xa.system.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;

import cn.zhx.xa.model.vo.index.ValidateCodeVo;
import cn.zhx.xa.system.service.ValidateCodeService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static cn.zhx.xa.model.constant.RedisKey.CODE_EXPIRE_DAYS;
import static cn.zhx.xa.model.constant.RedisKey.USER_LOGIN_CODE;


@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate ;

    @Override
    public ValidateCodeVo generateValidateCode() {

        // 使用hutool工具包中的工具类生成图片验证码
        //参数：宽  高  验证码位数 干扰线数量
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);
        String codeValue = circleCaptcha.getCode();
        String imageBase64 = circleCaptcha.getImageBase64();

        // 生成uuid作为图片验证码的key
        String codeKey = UUID.randomUUID().toString().replace("-", "");

        // 将验证码存储到Redis中
        stringRedisTemplate.opsForValue().set(USER_LOGIN_CODE + codeKey , codeValue ,CODE_EXPIRE_DAYS  , TimeUnit.MINUTES);

        // 构建响应结果数据
        ValidateCodeVo validateCodeVo = new ValidateCodeVo() ;
        validateCodeVo.setCodeKey(codeKey);
        validateCodeVo.setCodeValue("data:image/png;base64," + imageBase64);

        // 返回数据
        return validateCodeVo;
    }
}